package controller.filemanager;

import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.filemanager.FileManager;
import model.filemanager.MediaFile;

import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;


@SuppressWarnings("serial")
public class DownloadServlet extends HttpServlet {

	@Override
    public void doGet(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {

    	BlobKey blobKey = new BlobKey(req.getParameter("key"));
    	String download = req.getParameter("download");
		BlobInfoFactory factory = new BlobInfoFactory();
		BlobInfo info = factory.loadBlobInfo(blobKey);
        BlobstoreServiceFactory.getBlobstoreService().serve(blobKey, res);
        if (download != null && download.contentEquals("yes"));
        	res.setHeader("Content-Disposition","attachment; filename=\"" + info.getFilename() + "\";");
    }
	
	@Override
    public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {

			UserService userService = UserServiceFactory.getUserService();
			User user = userService.getCurrentUser();
        	String indexString = req.getParameter("index");
        	String listString = req.getParameter("list");
        	String sort = req.getParameter("sort");
        	String descString = req.getParameter("desc");
        	int index, list;
        	boolean desc = false;
        	try
        	{
        		index = Integer.parseInt(indexString);
        		list = Integer.parseInt(listString);
        		desc = Boolean.parseBoolean(descString);
        	}
        	catch(Exception e)
        	{
        		return;
        	}
        	Integer[] totalCount = new Integer[1];
        	FileManager fm = new FileManager(user.getEmail());
        	if (sort.length() == 0)
        		sort = null;
        	try {
				List<MediaFile> files = fm.SearchForFiles("audio", null, null, sort, list, desc, index, 1, totalCount);
	        	if (totalCount[0] > 0)
	        	{
	        		if (files.size() == 0)
	        		{
	        			files = fm.SearchForFiles("audio", null, null, sort, list, desc, 0, 1, totalCount);
	        			index = 0;
	        		}
	        		MediaFile file = files.get(0);
	        		String output = String.format("{\"title\":\"%s\", \"key\":\"%s\", \"index\":%d, \"count\":%d}", file.getProperty("title"), file.getKey(), index, totalCount[0]);
	        		res.setContentType("application/json");
	        		res.getWriter().println(output);
	        	}

			} catch (EntityNotFoundException e) {
				// TODO Auto-generated catch block
				return;
			}

        	
        }
}